<template>
  <div class="user-manage">
    <a-form layout="vertical">
      <a-card title="用户管理" :bordered="false">
        <div class="table-operations">
          <a-button type="primary" @click="showAddUser">
            <plus-outlined />添加用户
          </a-button>
          <a-button style="margin-left: 8px" @click="fetchUsers">
            <reload-outlined />刷新
          </a-button>
        </div>

        <a-table :columns="columns" :data-source="users" :loading="loading" :pagination="false"
          style="margin-top: 16px">
          <template #role="{ text }">
            <a-tag :color="text === 'admin' ? 'blue' : 'green'">
              {{ text === 'admin' ? '管理员' : '普通用户' }}
            </a-tag>
          </template>

          <template #status="{ text }">
            <a-badge :status="text === 'active' ? 'success' : 'default'" :text="text === 'active' ? '启用' : '禁用'" />
          </template>

          <template #lastLogin="{ text }">
            {{ formatTimestamp(text) }}
          </template>

          <template #action="{ record }">
            <a-space>
              <a-button type="link" size="small" @click="handleEdit(record)" :disabled="record.username === 'admin'">
                编辑
              </a-button>
              <a-button type="link" size="small" @click="handleResetPassword(record)">
                重置密码
              </a-button>
              <a-button type="link" danger size="small" @click="handleDelete(record)"
                :disabled="record.username === 'admin'">
                删除
              </a-button>
            </a-space>
          </template>
        </a-table>
      </a-card>
    </a-form>

    <a-modal v-model:visible="userModalVisible" :title="isEdit ? '编辑用户' : '添加用户'" @ok="handleSubmit"
      @cancel="handleCancel" :confirmLoading="submitting">
      <a-form ref="userForm" :model="userForm" :rules="rules" layout="vertical">
        <a-form-item label="用户名" name="username" :rules="[
          { required: true, message: '请输入用户名' },
          { min: 4, message: '用户名至少4个字符' }
        ]">
          <a-input v-model:value="userForm.username" :disabled="isEdit" placeholder="请输入用户名" />
        </a-form-item>

        <a-form-item v-if="!isEdit" label="密码" name="password" :rules="[
          { required: true, message: '请输入密码' },
          { min: 6, message: '密码至少6个字符' }
        ]">
          <a-input-password v-model:value="userForm.password" placeholder="请输入密码" />
        </a-form-item>

        <a-form-item v-if="!isEdit" label="确认密码" name="confirmPassword" :rules="[
          { required: true, message: '请确认密码' },
          { validator: validateConfirmPassword }
        ]">
          <a-input-password v-model:value="userForm.confirmPassword" placeholder="请确认密码" />
        </a-form-item>

        <a-form-item label="用户角色" name="role" v-if="isEdit">
          <a-radio-group v-model:value="userForm.role">
            <a-radio value="user">普通用户</a-radio>
            <a-radio value="admin">管理员</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item name="status" v-if="isEdit">
          <a-radio-group v-model:value="userForm.status">
            <a-radio value="active">启用</a-radio>
            <a-radio value="disabled">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal v-model:visible="deleteModalVisible" title="删除用户" @ok="confirmDelete" @cancel="cancelDelete"
      :confirmLoading="submitting" :okButtonProps="{ danger: true }" okText="删除">
      <p>确定要删除用户 "{{ selectedUser?.username }}" 吗？此操作不可恢复。</p>
    </a-modal>

    <a-modal v-model:visible="resetPasswordModalVisible" title="重置密码" @ok="confirmResetPassword"
      @cancel="cancelResetPassword" :confirmLoading="submitting">
      <a-form :model="resetPasswordForm" layout="vertical">
        <a-form-item label="原密码" name="oldPassword" :rules="[
          { required: true, message: '请输入原密码' }
        ]">
          <a-input-password v-model:value="resetPasswordForm.oldPassword" placeholder="请输入原密码" />
        </a-form-item>
        <a-form-item label="新密码" name="newPassword" :rules="[
          { required: true, message: '请输入新密码' },
          { min: 6, message: '密码至少6个字符' }
        ]">
          <a-input-password v-model:value="resetPasswordForm.newPassword" placeholder="请输入新密码" />
        </a-form-item>
        <a-form-item label="确认新密码" name="confirmNewPassword" :rules="[
          { required: true, message: '请确认新密码' },
          { validator: validateResetPasswordConfirm }
        ]">
          <a-input-password v-model:value="resetPasswordForm.confirmNewPassword" placeholder="请确认新密码" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, reactive, ref, toRefs, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { PlusOutlined, ReloadOutlined } from '@ant-design/icons-vue';
import request from '../../utils/request';

export default defineComponent({
  name: 'UserManage',
  components: {
    PlusOutlined,
    ReloadOutlined
  },
  setup() {
    const columns = [
      {
        title: '用户名',
        dataIndex: 'username',
        key: 'username'
      },
      {
        title: '角色',
        dataIndex: 'role',
        key: 'role',
        slots: { customRender: 'role' }
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        slots: { customRender: 'status' }
      },
      {
        title: '最后登录时间',
        dataIndex: 'last_login',
        key: 'lastLogin',
        slots: { customRender: 'lastLogin' }
      },
      {
        title: '操作',
        key: 'action',
        slots: { customRender: 'action' }
      }
    ];

    const state = reactive({
      users: [],
      loading: false,
      userModalVisible: false,
      deleteModalVisible: false,
      resetPasswordModalVisible: false,
      submitting: false,
      isEdit: false,
      selectedUser: null,
      userForm: {
        username: '',
        password: '',
        confirmPassword: '',
        role: 'user',
        status: 'active'
      },
      resetPasswordForm: {
        oldPassword: '',
        newPassword: '',
        confirmNewPassword: ''
      }
    });

    const validateConfirmPassword = async (rule, value) => {
      if (state.userForm.password && value !== state.userForm.password) {
        throw new Error('两次输入的密码不一致');
      }
    };

    const validateResetPasswordConfirm = async (rule, value) => {
      if (state.resetPasswordForm.newPassword && value !== state.resetPasswordForm.newPassword) {
        throw new Error('两次输入的密码不一致');
      }
    };

    const formatTimestamp = (timestamp) => {
      if (!timestamp) return '-';
      return new Date(timestamp * 1000).toLocaleString();
    };

    const fetchUsers = async () => {
      state.loading = true;
      try {
        const response = await request.get('/v1/users');
        state.users = response.data;
      } catch (error) {
        message.error(error.message || '获取用户列表失败');
      } finally {
        state.loading = false;
      }
    };

    const showAddUser = () => {
      state.isEdit = false;
      state.userForm = {
        username: '',
        password: '',
        confirmPassword: '',
        role: 'user',
        status: 'active'
      };
      state.userModalVisible = true;
    };

    const handleEdit = (user) => {
      state.isEdit = true;
      state.userForm = {
        username: user.username,
        role: user.role,
        status: user.status
      };
      state.userModalVisible = true;
    };

    const handleDelete = (user) => {
      state.selectedUser = user;
      state.deleteModalVisible = true;
    };

    const handleResetPassword = (user) => {
      state.selectedUser = user;
      state.resetPasswordForm = {
        oldPassword: '',
        newPassword: '',
        confirmNewPassword: ''
      };
      state.resetPasswordModalVisible = true;
    };

    const handleSubmit = async () => {
      state.submitting = true;
      try {
        if (state.isEdit) {
          await request.put(`/v1/users/${state.userForm.username}`, {
            role: state.userForm.role,
            status: state.userForm.status
          });
          message.success('用户信息已更新');
        } else {
          await request.post('/v1/users', {
            username: state.userForm.username,
            password: state.userForm.password
          });
          message.success('用户已添加');
        }
        await fetchUsers();
        state.userModalVisible = false;
      } catch (error) {
        message.error(error.message || (state.isEdit ? '更新失败' : '添加失败'));
      } finally {
        state.submitting = false;
      }
    };

    const confirmDelete = async () => {
      state.submitting = true;
      try {
        await request.delete(`/v1/users/${state.selectedUser.username}`);
        message.success('用户已删除');
        await fetchUsers();
        state.deleteModalVisible = false;
      } catch (error) {
        message.error(error.message || '删除失败');
      } finally {
        state.submitting = false;
      }
    };

    const confirmResetPassword = async () => {
      state.submitting = true;
      try {
        const response = await request.put(`/v1/users/${state.selectedUser.username}/password`, {
          old_password: state.resetPasswordForm.oldPassword,
          new_password: state.resetPasswordForm.newPassword
        });
        if (response.code === 200) {
          message.success('密码已重置');
          state.resetPasswordModalVisible = false;
        } else {
          throw new Error(response.error || '重置密码失败');
        }
      } catch (error) {
        message.error(error.message || '重置密码失败');
      } finally {
        state.submitting = false;
      }
    };

    const handleCancel = () => {
      state.userModalVisible = false;
    };

    const cancelDelete = () => {
      state.deleteModalVisible = false;
      state.selectedUser = null;
    };

    const cancelResetPassword = () => {
      state.resetPasswordModalVisible = false;
      state.selectedUser = null;
    };

    onMounted(() => {
      fetchUsers();
    });

    return {
      columns,
      ...toRefs(state),
      validateConfirmPassword,
      validateResetPasswordConfirm,
      formatTimestamp,
      fetchUsers,
      showAddUser,
      handleEdit,
      handleDelete,
      handleResetPassword,
      handleSubmit,
      handleCancel,
      confirmDelete,
      cancelDelete,
      confirmResetPassword,
      cancelResetPassword
    };
  }
});
</script>

<style scoped>
.user-manage {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.table-operations {
  margin-bottom: 16px;
}

:deep(.ant-table-cell) {
  padding: 8px 16px !important;
}

.ant-form-item {
  margin-bottom: 16px;
}
</style>
